package com.zhengjiang.controller;

import com.zhengjiang.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;

@RestController
@RequestMapping("/consumer")
public class StudentHandler {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/index")
    public String index(){
        /**
         *
         * 在 RestTemplate 配置上添加注解：@LoadBalanced
         * 基于 Ribbon 的负载均衡
         * 通过 RestTemplate 调用 Provider 相关接口，
         * RestTemplate 访问的 URL 不需要指定 IP 和 端口，直接访问 Provider 在 Eureka Server 注册的 application name 即可，
         * 比如：http://localhost:8010/ 必须替换为 http://provider/。
         */
        return restTemplate.getForObject("http://provider/student/index",String.class);
    }


    @GetMapping("/findAll")
    public Collection<Student> findAll(){
        // return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
        return restTemplate.getForObject("http://provider/student/findAll",Collection.class);
    }

    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") long id){
        //return restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);
        return restTemplate.getForObject("http://provider/student/findById/{id}",Student.class,id);
    }

    @PostMapping("/save")
    public void save(@RequestBody Student student){
        //restTemplate.postForObject("http://locahost:8010/student/save",student,Student.class);
        restTemplate.postForObject("http://provider/student/save",student,Student.class);
    }

    @PutMapping("/update")
    public void update(@RequestBody Student student){
        //restTemplate.postForObject("http://locahost:8010/student/update",student,Student.class);
        restTemplate.postForObject("http://provider/student/update",student,Student.class);
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        //restTemplate.getForObject("http://localhost:8010/student/deleteById/{id}",Student.class,id);
        restTemplate.getForObject("http://provider/student/deleteById/{id}",Student.class,id);
    }
}
